package org.example.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.models.R;
import org.example.service.PermissionsService;
import org.example.service.UserService;
import org.example.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

// OncePerRequestFilter:spring提供的过滤器处理类，如果按照servlet api的话，那么我们的过滤器就实现filter接口
@Component
public class TokenFilter extends OncePerRequestFilter {
    ObjectMapper objectMapper = new ObjectMapper();

//     添加所有需要忽略的路径
    List<String> ignoreURL = Arrays.asList(
            "/system/user/log",
            "/index",

            "/into/**",
            "/regularization/**",

            "/jobTransfer/**",
            "/jobtransfer/**",
            "/resignation/**",
            "/dimission/**",
            "/leave/**",

            "/contract/**",
            "/employeeContract/**",

            "/api/**"
    );

    AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
                String uri = request.getRequestURI();
        boolean flag = ignoreURL.stream().anyMatch(item -> antPathMatcher.match(item, uri));
        if (flag) {//是白名单地址，允许执行
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader("token");
        if (token == null) {
            response.setCharacterEncoding("utf-8");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            R error = R.error(401, "你还未登录，请重新登录");
            String json = objectMapper.writeValueAsString(error);
            response.getWriter().write(json);
            return;
        }
        boolean isExpired = JwtUtils.isExpired(token);
        if (isExpired) {
            response.setCharacterEncoding("utf-8");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            R error = R.error(401, "令牌已过期，请重新登录");
            String json = objectMapper.writeValueAsString(error);
            response.getWriter().write(json);
            return;
        }
        // 如果上面校验token成功，那么手动创建security的凭证对象
        Integer userId = JwtUtils.getId(token);
        String username = JwtUtils.getUsername(token);
        request.setAttribute("userId", userId);
        request.setAttribute("username", username);
        // 继续往下执行
        filterChain.doFilter(request, response);
    }
}
